<template>
    <Dialog :dialog-visible="data.visible" title="注册" width="500px" @confirm="handleConfirm" @close="close">
        <div class="dialog-form">
            <el-form :model="data.form" :rules="data.rules" ref="formRef" label-position="top">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="data.form.username" placeholder="请输入用户名" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="data.form.password" placeholder="请输入密码" type="password" show-password />
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input v-model="data.form.confirmPassword" placeholder="请输入密码" type="password" show-password />
                </el-form-item>
            </el-form>
        </div>

    </Dialog>
</template>

<script setup>
import Dialog from '@com/dialog/index.vue'
import { reactive, ref } from 'vue'
import { register } from '@/api/auth'
import { useMessage } from '@/hooks/useMessage'

const message = useMessage()


const validateConfirmPassword = (rule, value, callback) => {
    if (value !== data.form.password) {
        callback(new Error('两次密码不一致'))
    } else {
        callback()
    }
}

const data = reactive({
    visible: false,
    form: {
        username: '',
        password: '',
        confirmPassword: ''
    },
    rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }, { min: 6, max: 16, message: '密码长度为6-16位', trigger: 'blur' }],
        confirmPassword: [{ required: true, message: '请输入确认密码', trigger: 'blur' }, { validator: validateConfirmPassword, trigger: 'blur' }]
    }
})

const formRef = ref(null)

const open = () => {
    data.visible = true
}

const close = () => {
    data.form = {
        username: '',
        password: '',
        confirmPassword: ''
    }
    data.visible = false
}

const handleConfirm = async () => {
    const valid = await formRef.value.validate()
    if (valid) {
        const params = {
            username: data.form.username,
            password: data.form.password
        }

        const res = await register(params)
        console.log(res)
        if (res.code === 200) {
            message.alertMessage('注册成功', 'success')
            close()
        }
    }

}

defineExpose({
    open
})
</script>

<style scoped lang="scss">
.dialog-form {
    width: 100%;
    box-sizing: border-box;
    padding: 20px;

}
</style>